﻿
var gLastActiveGroupID='group_0';
var gGroupList=[];
var gPluginPath=external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME);
$(function(){
	document.body.onclick=function()
	{
		document.getElementById('groupMenu').style.display='none';
	}
    CreateGroup();
	    //$("#imgList").sortable({});
	    $("#imgList").sortable({
		stop: function() 
			{
				SaveImageList();
				RefreshNumber();
			}
	    });
});


function SelectAllImg(isSelect)
{
	if(isSelect)
	{
		$("#imgList li").addClass("selected");
	}
	else
	{
		$("#imgList li").removeClass("selected");
	}
}

function AddImgToList()
{
	window.showModalDialog("textarea.html",window,"status:0;help:0;scroll:0;resizable:0;center:1;dialogHeight:400px;dialogWidth:600px");
}
function EditWinClose(urlsText)
{
	if(urlsText)
	{
		var urls=urlsText.split("\r\n");
		html=[];
		var groupID=gLastActiveGroupID.split("_")[1];
	    var groupName=gGroupList[groupID];
	    var path="userData\\image\\"+groupName+"\\";		
		for(var i=0;i<urls.length;i++)
		{
			var imgSrc=trim(urls[i]);
			if(imgSrc)
			{
				var imgLocFn=encodeURIComponent(imgSrc)+".png";
    			var imgLocSrc=gPluginPath+path+ imgLocFn;
			//	html.push("<li onclick='$(this).toggleClass(\"selected\");'><span class='number'></span><span onclick='ShowLocImgName(\"",imgSrc,"\");' class='smallImg'><img src='",imgLocSrc,"' /></span><a href='",imgSrc,"' onmouseenter='showPopImg(this);' onmouseleave='hidePopImg();' target='_blank'>",imgSrc,"</a></li>");

		html.push("<li onclick='$(this).toggleClass(\"selected\");'><span class='number'></span><span  onclick='ShowLocImgName(\"",imgSrc,"\");'  class='smallImg'><img src='",imgLocSrc,"' /></span><a href='",imgSrc,"' title='",imgSrc,"' onclick='return changeTitle(this);' onmouseenter='showPopImg(this);' onmouseleave='hidePopImg();' target='_blank'>",imgSrc,"</a></li>");
				
			}
		}
		if(html.length>0)
		{
			$("#imgList").append(html.join(""));
			SaveImageList();
			$("#imgList").sortableRefresh({});
			RefreshNumber();
		}
	}
}

function ShowLocImgName(imgName)
{
	document.getElementById("messageBox").innerHTML="<button onclick='RegetImg(\""+imgName+"\")'>重新获取缩略图</button>："+encodeURIComponent(imgName);
}

function RegetImg(src)
{
	var groupID = gLastActiveGroupID.split("_")[1];
	var groupName=gGroupList[groupID];
	if(getImg(src,groupName,true)==0)
	{
		openPath('tool\\temp');
		ReloadLocImg();
	}
	else
	{
		alert("获取缩略图失败！");
	}

	//alert(src);
}

function ReloadLocImg()
{
	var r="?r1="+ Math.random();
	$("#imgList li span img").each(function(){
	//alert(this.src);
	this.src=this.src+r;
	});
}


function OpenImgPath()
{
	openPath('userData\\image');
}

function openPath(path)
{
	var ws= external.max_activex(SECURITY_ID,'WScript.Shell'); 

	var r= ws.run('cmd /C cd /d "'+gPluginPath+path+'" &start .',0);
	ws=null;	
}


function RefreshNumber()
{
	var liNumber=$("#imgList li span.number");
	liNumber.each(function(i){this.innerText=i+1;});
	var count=liNumber.length;
	var msg="当前组共有表情:"+count+"个, 每页显示:"+pharaoh_Config.X*pharaoh_Config.Y+"个, 需要显示:"+Math.ceil(count/(pharaoh_Config.X*pharaoh_Config.Y))+"页";

//	if(count>pharaoh_Config.X*pharaoh_Config.Y)
//	{
//		msg="<font color='red'>"+msg+"  可以显示表情个数："+pharaoh_Config.X*pharaoh_Config.Y+ "</font>";
//	}	
	document.getElementById("messageBox").innerHTML=msg;
}

function MoveImgToGroup()
{
	var gMenu=document.getElementById('groupMenu');

	var html=[];
	var curGroupID = gLastActiveGroupID.split("_")[1];
	for(var i=0;i<gGroupList.length;i++)
	{
		if(i!=curGroupID)
		{
			html.push('<li id=menu_'+i+'>'+gGroupList[i]+'</li>');
		}
	}

	gMenu.innerHTML=	html.join("");
	var p=document.getElementById('moveGroupButton').getBoundingClientRect();
	
	var w=p.right-p.left;
	gMenu.style.width=w;
	gMenu.style.top=p.bottom;
	gMenu.style.left=p.left;
	gMenu.style.display='block';

	event.cancelBubble = true;
	var gLi=$("#groupMenu li");
	gLi.click(function(){
	//	alert(this.innerText);
		MoveToOtherGroup(this.id.split("_")[1]);
		});
		gLi.hover(function(){
		  $(this).addClass("hover");
		},function(){
		  $(this).removeClass("hover");
		});
		
}

function MoveToOtherGroup(newGroupID)
{
	var groupID = gLastActiveGroupID.split("_")[1];
	var groupName=gGroupList[groupID];
	var newGroupName=gGroupList[newGroupID];
	var groupPath="userData\\image\\"+groupName+"\\";
	var newGroupPath="userData\\image\\"+newGroupName+"\\";
	var selectImage=$("#imgList li.selected");
	var urlsToMove=[];
	if(selectImage.length>0)
	{
			$("#imgList li.selected a").each(function(){
				urlsToMove.push(this.href);
				var locName=encodeURIComponent(this.href)+".???";
				try
				{
					fso.MoveFile(gPluginPath+groupPath+locName,gPluginPath+newGroupPath); 
				}
				catch(e)
				{
				}
				this.href="";		
			});
			SaveImageList();
			LoadImageList(groupID);	
			var newGroupUrlText=external.readFile(SECURITY_ID,PLUGIN_NAME,newGroupPath+"list.txt");	
			var newGroupUrls=[];
			if(newGroupUrlText)
			{
				newGroupUrlText=clear0(newGroupUrlText);
				newGroupUrls=trim(newGroupUrlText).split("\r\n");
			}
			newGroupUrls = newGroupUrls.concat(urlsToMove);
			external.writeFile(SECURITY_ID,PLUGIN_NAME,newGroupPath+"list.txt",newGroupUrls.join("\r\n"));	
	}	
}

function DeleteImgFromList()
{
	var groupID = gLastActiveGroupID.split("_")[1];
	var groupName=gGroupList[groupID];
	var selectImage=$("#imgList li.selected");
	var path=gPluginPath+"userData\\image\\"+groupName+"\\";
	if(selectImage.length>0)
	{
		if(window.confirm("确定要删除选中的“"+selectImage.length+"”个表情？"))
		{
			$("#imgList li.selected a").each(function(){
				var locName=encodeURIComponent(this.href)+".???";
				try
				{
				fso.DeleteFile(path+locName,true);
				}
				catch(e)
				{
				}
				this.href="";
				//DONE:删除缩略图。
				
			});
			SaveImageList();
			LoadImageList(groupID);
		}
	}
	else
	{
		alert("请先选择需要删除的表情！");
		return;
	}
}


function SaveImageList()
{
	var urls=[];
	$("#imgList li a").each(function(){ 
		var h=trim(this.href);
		if(h)
		{
			urls.push(h); 
		}
	});
	//alert(urls);
	var groupName=gGroupList[gLastActiveGroupID.split("_")[1]];
	try
	{
	fso.CreateFolder(gPluginPath+"userData\\image\\"+groupName);
	}
	catch(e){}
	external.writeFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\"+groupName+"\\list.txt",urls.join("\r\n"));					
}


function CreateGroup()
{    
    var groupText=external.readFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\groups.txt");
    if(groupText)
    {
    	groupText=clear0(groupText);
        gGroupList=groupText.split("\r\n");
    }
    gGroupList=["TEMP"].concat(gGroupList);
    var html=[];
    for(var i=0;i<gGroupList.length;i++)
    {
        html.push("<li id='group_",i,"'>",gGroupList[i],"</li>");
    }
    $('#groupList').html(html.join(""));
    
    $('#group_0').addClass('current');
    LoadImageList(0);
    $('#groupList li').click(function(o){
        //printobj(this);
        if(this.className=='current') {return;}
        $('#'+gLastActiveGroupID).removeClass('current');
        gLastActiveGroupID=this.id;
        $('#'+gLastActiveGroupID).addClass('current');
        LoadImageList(gLastActiveGroupID.split("_")[1]);
        
    });
}



function LoadImageList(groupID)
{
    var groupName=gGroupList[groupID];
    //alert('Load:'+groupName);    
	var gImgList=[];
    var path="userData\\image\\"+groupName+"\\";
    var imgText=external.readFile(SECURITY_ID,PLUGIN_NAME,path+"list.txt");
    //alert(imgText);
    if(imgText)
    {
    	imgText=clear0(imgText);
    	gImgList=imgText.split("\r\n");
    }
    var html=[];
    r=Math.random();
    for(var i=0;i<gImgList.length;i++)
    {
    	var imgSrc=gImgList[i];
    	var locImgName=encodeURIComponent(imgSrc);
    	var imgLocFn=locImgName+".png";
    	var imgLocSrc=gPluginPath+path+ imgLocFn+"?r="+r;
		var imgName=external.readFile(SECURITY_ID,PLUGIN_NAME,path+locImgName+".txt");
		//alert(imgName);
		if(imgName)
		{
			imgName=clear0(imgName);
			imgName="【"+imgName+"】"+imgSrc;
		}
		else
		{
			imgName=imgSrc;
		}
		html.push("<li onclick='$(this).toggleClass(\"selected\");'><span class='number'></span><span  onclick='ShowLocImgName(\"",imgSrc,"\");'  class='smallImg'><img src='",imgLocSrc,"' /></span><a href='",imgSrc,"' title='",imgSrc,"' onclick='return changeTitle(this);' onmouseenter='showPopImg(this);' onmouseleave='hidePopImg();' target='_blank'>",imgName,"</a></li>");
    	
    	//html.push("<li onclick='$(this).toggleClass(\"selected\");'><span class='number'></span><span class='smallImg'><img src='",imgLocSrc,"' /></span><a href='",imgSrc,"' onmouseenter='showPopImg(this);' onmouseleave='hidePopImg();' target='_blank'>",imgSrc,"</a></li>");
    }
    $('#imgList').html(html.join(''));

    $("#imgList").sortableRefresh({});
    RefreshNumber();
}

function changeTitle(link)
{
	if(event.shiftKey)
	{
		return true;
	}
	var groupID = gLastActiveGroupID.split("_")[1];
	var groupName=gGroupList[groupID];
	var fn="userData\\image\\"+groupName+"\\"+encodeURIComponent(link.href)+".txt";
	var imgName=external.readFile(SECURITY_ID,PLUGIN_NAME,fn);
	
	if(!imgName)
	{
		imgName="";
	}
	imgName=clear0(imgName);
	imgName = prompt("请输入表情名称：",imgName);
	
	if(imgName==undefined){return false;}
	if(!imgName)
	{
		imgName='';
	}
	else
	{
		imgName=trim(imgName);
	}
	//alert(link.innerText);
	if(imgName)
	{
		link.innerText="【"+imgName+"】"+link.href;
	}
	else
	{
		link.innerText=link.href;
	}
	external.writeFile(SECURITY_ID,PLUGIN_NAME,fn,imgName);
	return false;
}

function AddGroup()
{
    alert('//todo:AddGroup');
}

function EditGroup()
{
    var groupID=gLastActiveGroupID.split('_')[1];
    if(groupID==0)
    {
        alert('不能更改TEMP的名称!\n请新建一个组，将表情移动到对应的组中。');
        return;
    }
    
    var groupName=gGroupList[gLastActiveGroupID.split('_')[1]];

    var newGroupName = window.prompt("请输入新的组名称(首尾的空格会被去掉)：",groupName);

    if(newGroupName)
    {
        
        newGroupName=trim(newGroupName);      
        if(!newGroupName) {return;}
        var lGroupName=newGroupName.toLowerCase();
        if(lGroupName==groupName.toLowerCase())
        {
            //alert('名称没有更改');
            return;
        }
        var index= indexOfinArray(gGroupList,lGroupName);
        if(index>=0)
        {
            alert("已经存在同名的组，更名没有成功！");
            return;        
        }
        
        var path= gPluginPath+"userData\\image\\";
        var returnText = DirRename(path+ groupName,path+newGroupName);
        if(returnText)
        {
            alert("更改组名称错误！\n"+returnText);
            return;
        }

        gGroupList[groupID]=newGroupName;
        $('#'+gLastActiveGroupID).text(newGroupName);
        
        var newGroupList=gGroupList.slice(1);
        external.writeFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\groups.txt",newGroupList.join("\r\n"));
        
    }
}

function DeleteGroup()
{
    alert('//todo:DeleteGroup');
}

function DownloadImg()
{
    var groupID=gLastActiveGroupID.split('_')[1];
    
    var groupName=gGroupList[groupID];
	

	
	var urls=[];
	//var urls=gImgList;
	$("#imgList li a").each(function(){urls.push(this.href);});

	var getImgList=[];
	var getImgCount=0;
	var mb=window.document.getElementById("messageBox");
	for(var i=0;i<urls.length;i++)
	{
		mb.innerText="正在获取图片缩略图：["+(i+1)+"/"+urls.length+"]:"+urls[i];
		var r= getImg(urls[i],groupName);
		if(r==0)
		{
			getImgCount++;
		}
		/*
		if((r==0)||(r==-1))
		{
			getImgList.push(encodeURIComponent(urls[i]));
		}
		*/
	}
	//window.external.writeFile(SECURITY_ID,PLUGIN_NAME,"userData\\image\\temp\\getOK.txt",getImgList.join("\r\n"));
	mb.innerText="获取完成！"+"["+getImgCount +"/"+urls.length+"] " ;
	//alert(gLastActiveGroupID);
	if(getImgCount>0)
	{
		//LoadImageList(groupID);
		ReloadLocImg();
	}
}
function getImg(imgPath,groupName,isReget)
{
	var fso=external.max_activex(SECURITY_ID,"Scripting.FileSystemObject");

	var pharaoh_pluginPath=external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME);
	
	var dosFn= groupName + "\\" +encodeURIComponent(imgPath);
	if(!isReget)
	{

		if(fso.FileExists(pharaoh_pluginPath+"userData\\image\\"+dosFn+".png")) 
		{
			return -1;
		}
	}
	var ws= external.max_activex(SECURITY_ID,'WScript.Shell'); 
	//alert(path);
	//ws.run('notepad.exe "'+external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME)+'autorunUrl.lst"')
//	var r= ws.run('cmd.exe /C "'+external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME)+'tool\\good\\getimg.bat" "http://www.imagemagick.com/images/fuzzy-magick.png"',5,true);
	var batFn="tool\\getimg.txt";

    //var bat=window.external.readFile(SECURITY_ID,PLUGIN_NAME,batFn);
    var f= fso.OpenTextFile(pharaoh_pluginPath+batFn,1);
    bat=f.ReadAll();
    //bat=clear0(bat);
    //alert(bat);

    bat= bat.replace(/IMAGE_PATH/g,imgPath);
    bat=bat.replace(/IMAGE_NAME/g, dosFn.replace(/%/g,"%%"));

	f=fso.OpenTextFile(pharaoh_pluginPath+"tool\\tmpBat.bat",2,true);
	f.Write(bat);
	f.Close();
    //window.external.writeFile(SECURITY_ID,PLUGIN_NAME,"tool\\tmpBat.bat",bat);
    
    f= fso.OpenTextFile(pharaoh_pluginPath+"tool\\setImg.txt",1);
    bat=f.ReadAll();
    //bat=window.external.readFile(SECURITY_ID,PLUGIN_NAME,"tool\\setImg.txt");
	//bat=clear0(bat);
    bat= bat.replace(/IMAGE_PATH/g,imgPath);
    bat=bat.replace(/IMAGE_NAME/g, dosFn.replace(/%/g,"%%"));

	f=fso.OpenTextFile(pharaoh_pluginPath+"tool\\0拖动图片到此文件上设置缩略图.bat",2,true);
	f.Write(bat);
	f.Close();
    //window.external.writeFile(SECURITY_ID,PLUGIN_NAME,"tool\\0拖动图片到此文件上设置缩略图.bat",bat);
    
	var r= ws.run('cmd /C cd /d '+external.m2_plugin_folder(SECURITY_ID,PLUGIN_NAME)+'tool\\ &tmpBat.bat',7,true);
		//alert('pd');
	ws=null;
	return r;
}


function printobj(o)
{
	var msg='';
	for(var k in o)
	{
		msg+=k+"\t:"+o[k]+"\n";
	}
	alert(msg);
}


function indexOfinArray(list,str)
{
    var lstr=str.toLowerCase();
    for(var i=0;i<list.length;i++)
    {
        if(lstr==list[i].toLowerCase())
        {          
            return i;
        }
    }
    return -1;
}

var fso=external.max_activex(SECURITY_ID,"Scripting.FileSystemObject");
function DirRename(oldName,NewName)
{
    try
    {
    fso.MoveFolder(oldName,NewName);
    }
    catch(e)
    {
        return e.message;
    }
    return null;
}

var popWin=window.createPopup();
var ShowAgain;
var LastImg;
var LastImgX;
var LastImgY;
function showPopImg(imgLink)
{
	if(event.ctrlKey) return;
	LastImg=imgLink;
	//top.status=img.src;
	ShowAgain=true;
	LastImgX=event.screenX+10;
	LastImgY=event.screenY+30;
	popWin.document.body.innerHTML="<div style='border:1px solid gray;padding:2px;'><img src='"+imgLink.href+"' onload='parent.imgLoaded(this.width,this.height,this.src);' /></div>";
	popWin.show(LastImgX,LastImgY,36,36);
}

function hidePopImg()
{
	popWin.hide();
}
function imgLoaded(w,h,src)
{
	if(ShowAgain)
	{
		ShowAgain=false;
		//top.status="["+ w+","+h+"]"+src;
		if(popWin.isOpen)
		{
			popWin.show(LastImgX,LastImgY,w+6,h+6);	
		}
	}
}



